package com.sat.goods.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.sat.common.entity.Result;
import com.sat.goods.model.Goods;
import com.sat.goods.model.SkuVo;
import com.sat.goods.model.SpuVo;
import com.sat.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("goods")
@CrossOrigin //解决跨域问题
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @PostMapping
    public Result addGoods(@RequestBody Goods goods) {
        boolean b = goodsService.addGoods(goods);
        if (b) {
            return Result.OK("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    @GetMapping("{spuid}")
    public Result findBySpuid(@PathVariable Long spuid) {
        SpuVo bySpuid = goodsService.findBySpuid(spuid);
        return Result.OK(bySpuid);
    }

    @PutMapping
    public Result updataById(@RequestBody Goods goods) {
        boolean b = goodsService.updateGoods(goods);
        if (b) {
            return Result.OK("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    @DeleteMapping("{id}")
    public Result deleteById(@PathVariable Long id) {
        boolean b = goodsService.delete(id);
        if (b) {
            return Result.OK("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 批量上下架
     * @return
     */
    @PutMapping("listUpAndDown/{status}")
    public Result listUpAndDown(@RequestBody List<Long> spuIds,@PathVariable Integer status){
     boolean b=goodsService.listUpAndDown(spuIds,status);
        if (b) {
            return Result.OK("批量上架或下架成功");
        } else {
            return Result.error("批量上架或下架失败");
        }
    }

    /**
     *根据skuId得到skuVo
     * 微服务之间调用不用但会统一结果集
     * @param skuId
     * @return
     */
    @GetMapping("getBySkuId/{skuId}")
    public SkuVo getBySkuId(@PathVariable long skuId){
        SkuVo skuVo=goodsService.getBySkuId(skuId);

        return skuVo;
    }

    /**
     * 用户下单后更新库存
     * @param skuId
     * @param num
     * @return
     */
    @RequestMapping("updateInventory")
    public Integer updateInventory(String skuId ,Integer num){
        int i=goodsService.updateInventory(skuId,num);
        return i;
    }

}
